# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2009-04-02.
# $Id$
#

import logging
import urllib

from django.http import HttpRequest
from django.template import loader, Context

from google.appengine.api import users

from buggarden.foodsnroses import config

#---------------------------------------------------------------------------------------------------
# Django helper functions
#---------------------------------------------------------------------------------------------------

def create_context(request, ctxt_dict):
    """Adds additional name-value pairs to the context dict and returns a Django context."""
    
    user = users.get_current_user()
    if not user:
        sign_in_url = users.create_login_url(request.path)
        sign_out_url = None
        is_admin = False
    else:
        sign_in_url = None
        sign_out_url = users.create_logout_url(request.path)
        is_admin = user.email() in config.ADMIN_EMAILS
    
    server_url = 'http://%s' % request.META.get('SERVER_NAME')
    server_port = request.META.get('SERVER_PORT', '80').strip()
    if server_port and server_port != '80':
        server_url += ':%s' % server_port
    
    ctxt_dict.update({
        'user_': user,
        'sign_in_url_': sign_in_url,
        'sign_out_url_': sign_out_url,
        'is_admin_': is_admin,
        'server_url_': server_url,
        'path_': request.path,
        'is_ie_': (request.META.get('HTTP_USER_AGENT', '').find('IE') >= 0),
    })
    ctxt_dict.update(config.as_dict())
    
    return Context(ctxt_dict)


def get_template(name):
    """Loads and returns a Django template."""
    return loader.get_template('%s/%s' % (config.TMPL_ROOT, name))

#---------------------------------------------------------------------------------------------------
# URL creating functions
#---------------------------------------------------------------------------------------------------

def _encode_query_string(params):
    if params:
        # urllib.urlencode() cannot encode dict with mixed str/unicode.
        utf8_params = {}
        for key, value in params.items():
            if key and value:
                utf8_params[key.encode('utf8')] = value.encode('utf8')
        return urllib.urlencode(utf8_params)
    else:
        return ''


def create_url(path, params=None):
    """Returns a URL within this webapp."""
    url = '%s/%s' % (config.WEBAPP_URL_PREFIX, path)
    if params:
        return '%s?%s' % (url, _encode_query_string(params))
    else:
        return url

def create_error_url(message):
    """Returns a URL to the error page."""
    params = {'error': message,}
    return '%s/error/?%s' % (config.WEBAPP_URL_PREFIX, _encode_query_string(params))

def create_access_denied_url(path):
    """Returns a URL to the error page, with an access-denied error message."""
    return create_error_url('Access to "%s" is denied.' % path)


#---------------------------------------------------------------------------------------------------
# Prompt for information and error
#---------------------------------------------------------------------------------------------------

def create_error_param(message):
    """Returns a param dict containing the error message. The returned dict should be used as the
    query string appended to a URL. The typical usage is:
        params = create_error_param(message)
        url = 'some_url?%s' % urllib.encoding(params)
    """
    return {'error': message,}

def create_info_param(message):
    return {'info': message,}


class Prompt(object):

    NONE = 0
    INFO = 10
    ERROR = 20
    
    def __init__(self, query_dict, is_closeable=True):
        """Creates a Prompt object from the query dict. A prompt has 2 attributes:
        - severity : is the severity of this prompt, information or error.
        - message  : is the message of this prompt.
        """
        error_message = query_dict.get('error')
        info_message = query_dict.get('info')
        if error_message:
            self.severity = Prompt.ERROR
            self.message = error_message
        elif info_message:
            self.severity = Prompt.INFO
            self.message = info_message
        else:
            self.severity = Prompt.NONE
            self.message = None
        self.is_closeable = is_closeable
    
    def __nonzero__(self):
        return bool(self.message)
    
    def __unicode__(self):
        return self.message
    
    def id(self):
        return 'prompt%d' % hash(self)
    
    def severity_string(self):
        if self.severity >= Prompt.ERROR:
            return 'error'
        else:
            return 'info'
    
    @staticmethod
    def create_info(message):
        return Prompt(create_info_param(message))
    
    @staticmethod
    def create_error(message):
        return Prompt(create_error_param(message))







